package com.wodan.zhongjinjicang.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * 记录servlet层抛出异常的过滤器
 * 
 * @ClassName: LogServletErrorFilter
 * @author Administrator
 * @date 2015-7-27 下午5:27:46
 * @history
 * 
 */
public class LogServletErrorFilter implements Filter {
	private static final Logger LOGGER = LoggerFactory.getLogger(LogServletErrorFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 不实现

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		try {
			chain.doFilter(request, response);
		} catch (RuntimeException | IOException | ServletException ex) {
			if(ex.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
				// 忽略异常
				throw ex;
			}
			
			HttpServletRequest httpServletRequest = (HttpServletRequest) request; 
			
			JSONObject json = new JSONObject();
			json.put("requestURI", httpServletRequest.getRequestURI());
			json.put("queryString", httpServletRequest.getQueryString());
			json.put("parameterMap", httpServletRequest.getParameterMap());
			
			LOGGER.error("servlet处理抛出异常, 参数：[" + json.toJSONString() + "]" , ex);
			throw ex;
		}
	}

	@Override
	public void destroy() {
		// 不实现

	}

}
